import React, { forwardRef, useEffect, useState } from 'react'
import { Button, Modal, Form, Input, Select } from 'antd';

const UserForm = (props, ref) => {
	const [isDisabled, setisDisabled] = useState(false)
	const { Option } = Select;
	const { roleId, region, username } = JSON.parse(localStorage.getItem('token'))
	const roleObj = {
		1: 'superadmin',
		2: 'admin',
		3: 'editor'
	}
	useEffect(() => {
		setisDisabled(props.isEdit)

	}, [props.isEdit])

	const checkRegionDisabled = (item) => {
		if (props.isUpdate) {
			if (roleObj[roleId] == 'superadmin') {
				return false
			} else {
				return true
			}
		} else {
			if (roleObj[roleId] == 'superadmin') {
				return false
			} else {
				return item.value != region
			}
		}
	}
	const checkRoleDisabled = (item) => {
		if (props.isUpdate) {
			if (roleObj[roleId] == 'superadmin') {
				return false
			} else {
				return true
			}
		} else {
			if (roleObj[roleId] == 'superadmin') {
				return false
			} else {
				return item.id != 3
			}
		}
	}


	const roleChange = (val) => {
		if (val == 1) {
			setisDisabled(true)
			ref.current.setFieldsValue({
				region: ''
			})
		} else {
			setisDisabled(false)
		}
	}
	return (
		<>
			<Form
				ref={ref}
				name="basic"
				labelCol={{ span: 4 }}
				wrapperCol={{ span: 20 }}
				initialValues={{ remember: true }}
				// onFinish={onFinish}
				// onFinishFailed={onFinishFailed}
				layout="vertical"
				autoComplete="off"
			>
				<Form.Item
					label="用户名"
					name="username"
					rules={[{ required: true, message: 'Please input your username!' }]}
				>
					<Input />
				</Form.Item>
				<Form.Item
					label="密码"
					name="password"
					rules={[{ required: true, message: 'Please input your username!' }]}
				>
					<Input />
				</Form.Item>
				<Form.Item
					label="区域"
					name="region"
					rules={[{ required: !isDisabled, message: 'Please input your username!' }]}
				>
					<Select disabled={isDisabled}>
						{
							props.regionList.map(item => {
								return <Option key={item.id} disabled={checkRegionDisabled(item)} value={item.value}>{item.title}</Option>
							})
						}
					</Select>
				</Form.Item>
				<Form.Item
					label="角色"
					name="roleId"
					rules={[{ required: true, message: 'Please input your username!' }]}
				>
					<Select onChange={(val) => roleChange(val)}>
						{
							props.roleList.map(item => {
								return <Option key={item.id} disabled={checkRoleDisabled(item)} value={item.id} >{item.roleName}</Option>
							})
						}
					</Select>
				</Form.Item>
			</Form>

		</>
	)
}


export default forwardRef(UserForm)